import global from '@feidao-factory/send-msg/utils/global';
import service from '../../msg/service';
import { get } from '../network/request';

export interface IClientInfo {
	area: string;
	area_id: string;
	city: string;
	city_id: string;
	country: string;
	country_id: string;
	ip: string;
	isp_id: string;
	region_id: string;
	region: string;
	county: string;
	isp: string;
}

/**
 * 发起微信支付
 * @param systemid 项目systemid
 * @param trade_no 订单单号（最大长度32）
 * @param fee 商品金额
 * @param des 商品描述（最大长度128，不能为空）
 * @param openid 微信用户唯一标示
 * @param time_start 订单生成时间，格式为yyyyMMddHHmmss，如2009年12月25日9点10分10秒表示为20091225091010。
 * @param time_expire 订单失效时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010。注意：最短失效时间间隔必须大于5分钟 且存活时间不得超过两小时
 * @param usercode 用户code
 * @param attach 附加数据，原样返回；序列化后的字符串字节长度不能超过127
 */
export default async function request_payment(systemid: string, trade_no: string, fee: string, des: string, openid: string, time_start: string, time_expire: string, usercode: string, attach: { [key: string]: any }) {
	const url = `${global.host}/getip`;
	const rt = await get(url);
	const ip_info = rt.data as IClientInfo;
	const param = {
		BusinessKey: 'weixin',
		attach: JSON.stringify(attach),
		client_ip: ip_info.ip,
		des,
		fee,
		openid,
		systemid,
		thirdpay_type: 'weixin_applet',
		time_expire,
		time_start,
		trade_no,
		usercode
	};
	const info = await service<{ appId: string; timeStamp: string; nonceStr: string; package: string; signType: 'MD5' | 'HMAC-SHA256'; paySign: string; }>('thirdpart.weixinapplet.pay', param);
	return new Promise<boolean>((resolve, reject) => {
		wx.requestPayment({
			nonceStr: info.nonceStr,
			package: info.package,
			paySign: info.paySign,
			signType: info.signType,
			timeStamp: info.timeStamp,
			success(res) {
				console.log('success', res);
				resolve(true);
			},
			fail(e) {
				console.error(e);
				reject(false);
			}
		});
	});
}
